package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

/**
 * @author 吴
 * @version V1.0
 * @Description  预约信息
 * @Package com.itheima.service.Impl
 * @date 2021/11/27 13:18
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;

    /**
     * 提交预约信息
     * @param map  预约数据
     */
    @Override
    public Result saveOrderInfo(Map<String, String> map) throws Exception {

        // 将日期格式化
        String orderDate = map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        Date birthday = null;
        if(map.get("birthday")!=null) {
            String birthdays = map.get("birthday");
            birthday = DateUtils.parseString2Date(birthdays);
        }
        // 1、检查用户选择的日期是否可以进行预约，
        OrderSetting orderSetting = orderSettingDao.selectByOrderDate(date);
        if(orderSetting == null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        // 2、可以预约，预约人数是否已满
        if(orderSetting.getNumber() <= orderSetting.getReservations()){
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        // 3、通过手机号检查当前用户是否为会员，如果是会员则可以预约，如果不是会员则自动完成注册并进行预约
        Member member = memberDao.selectByTelephone(map.get("phoneNumber"));
        if(member == null){
            // 用户还没有注册成为会员，自动完成注册
            member=new Member();
            member.setName(map.get("name"));
            member.setSex(map.get("sex"));
            member.setIdCard(map.get("idCard"));
            member.setPhoneNumber(map.get("phoneNumber"));
            member.setBirthday(birthday);
            member.setRegTime(new Date());
            // 保存会员信息,保存之后需要获取到会员的id
            memberDao.addMember(member);
        }

        // 4、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐）
        Order order = new Order();
        order.setMemberId(member.getId());
        if (map.get("setmealId") != null) {
            order.setSetmealId(Integer.parseInt(map.get("setmealId")));
        }
        order.setOrderDate(date);

        List<Order> orderList = orderDao.findByCondition(order);//如果有值的话，说明已经有了
        if (orderList != null && orderList.size() > 0)
        {
            return new Result(false, MessageConstant.HAS_ORDERED);
        }
        order.setOrderType(map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSortingId(Integer.parseInt(map.get("sortingId")));

        orderDao.addOrder(order);  //添加订单信息，返回ID
        // 开始预约，预约成功，更新当日的已预约人数

        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.updateByOrderDate(orderSetting);
        // 短信提示用户预约成功


        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }



    /**
     *  根据预约Id 查询 （体检人名、体检套餐名、体检日期、预约类型）
     * @param orderId  预约Id
     */
    @Override
    public Order findMemberSetmealByOrderId(Integer orderId) {
        return orderDao.findMemSetmealByOrderId(orderId);
    }

    /**
     * 带条件分页查询检查组信息
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult selectByCondition(Map<String,String> queryPageBean) {

        String currentPage = queryPageBean.get("currentPage");
        String pageSize = queryPageBean.get("pageSize");
        PageHelper.startPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));

        List<Map> checkOrders =orderDao.selectByCondition(queryPageBean);

        PageInfo<Map> pageInfo = new PageInfo<>(checkOrders);

        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 根据id查询数据并回显
     * @param orderId
     * @return
     */
    @Override
    public Map<String, Object> findById(Integer orderId) {
        return orderDao.findById(orderId);
    }

    /**
     * 提交预约信息
     * @param map  预约数据
     */
    @Override
    public Result editOrderInfo(Map<String, String> map) throws Exception {
        try {
            // 将日期格式化
            String orderDate = map.get("orderDate");
            Date date = DateUtils.parseString2Date(orderDate);
            Date birthday = null;
            if(map.get("birthday")!=null) {
                String birthdays = map.get("birthday");
                birthday = DateUtils.parseString2Date(birthdays);
            }
            // 1、检查用户选择的日期是否可以进行预约，
            OrderSetting orderSetting = orderSettingDao.selectByOrderDate(date);
            if(orderSetting == null){
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }

            // 2、可以预约，预约人数是否已满
            if(orderSetting.getNumber() <= orderSetting.getReservations()){
                return new Result(false,MessageConstant.ORDER_FULL);
            }

            // 3、通过id查找当前用户，并进行修改
            Integer orderid = Integer.parseInt(map.get("id"));
            //根据orderid修改mumber信息
            Map<String,Object> member = new HashMap<>();
            member.put("orderId",orderid);
            member.put("name",map.get("name"));
            member.put("sex",map.get("sex"));
            member.put("idCard",map.get("idCard"));
            member.put("birthday",birthday);
            member.put("phoneNumber",map.get("phoneNumber"));
            //修改会员信息
            memberDao.updataByOrderId(member);
            //修改预约信息
            orderDao.updateById(map);
            return new Result(true,MessageConstant.ORDER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"失败");
        }
    }

    @Override
    public void changeStatus(Map<String,Object> map) {

        orderDao.changeStatus(map);
    }

    @Override
    public List<Integer> findOrderCountAndSetmealNameByBeforeDate(String[] beforeDates) {
        List<Integer> list = new ArrayList<>();

        Arrays.stream(beforeDates).forEach(date->{
            List<Setmeal>  list1 = orderDao.findOrderCountAndSetmealNameByBeforeDate(date);
            int income=0;
            if (list1.size()!=0){
                System.out.println(list1);
                for (Setmeal s : list1) {
                    income +=s.getPrice();
                }}
            list.add(income);
        });
        return list;
    }

    @Override
    public List<Map> findCountAndPay(String[] beforeDates) {
        List<Map> list = new ArrayList<>();
        List<Integer>list1=new ArrayList<>();
        List<Integer>list2=new ArrayList<>();
        Map<String,List>map=new HashMap<>();
        Arrays.stream(beforeDates).forEach(beforeDate->{
            Integer count1 = orderDao.findOrderCountBeforeDate(beforeDate);
            Integer count2 = orderDao.findPayCountBeforeDate(beforeDate);
            list1.add(count1);
            list2.add(count2);
        });
        map.put("order",list1);
        map.put("pay",list2);
        list.add(map);
        return list;
    }

    @Override
    public List<Sorting> findSortings() {
        return orderDao.findSortings();
    }
}
